package com.example.security;

import com.example.util.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * JWT认证过滤器
 */
@Component
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private UserDetailsServiceImpl userDetailsService;
    
    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain) throws ServletException, IOException {
        
        try {
            // 获取请求头中的Token
            final String authHeader = request.getHeader("Authorization");
            String username = null;
            String jwtToken = null;
            
            // 如果请求头中存在Token
            if (authHeader != null) {
                // 处理不同格式的Authorization头
                if (authHeader.startsWith("Bearer ")) {
                    // 标准格式: "Bearer xxx"
                    jwtToken = authHeader.substring(7).trim();
                } else if (authHeader.startsWith("bearer ")) {
                    // 小写格式: "bearer xxx"
                    jwtToken = authHeader.substring(7).trim();
                } else if (!authHeader.contains(" ")) {
                    // 只有token，没有Bearer前缀
                    jwtToken = authHeader.trim();
                }
                
                // 如果成功提取了token
                if (jwtToken != null && !jwtToken.isEmpty()) {
                    try {
                        username = jwtUtil.getUsernameFromToken(jwtToken);
                    } catch (Exception e) {
                        log.warn("JWT解析失败: {}", e.getMessage());
                    }
                }
            }
            
            // 如果从Token中获取到了用户名且当前请求未认证
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                // 根据用户名加载用户信息
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                
                // 验证Token
                if (jwtUtil.validateToken(jwtToken, userDetails.getUsername())) {
                    // 创建认证令牌
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            userDetails, null, userDetails.getAuthorities());
                    
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    
                    // 设置认证信息
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        } catch (Exception e) {
            log.error("JWT认证失败：", e);
        }
        
        filterChain.doFilter(request, response);
    }
} 